# @Time    : 2024/1/16 21:49
# @Author  : 🍁
# @File    : verify.py
# @Software: PyCharm
from django.views import View
from django import http
from django_redis import get_redis_connection
from django.core.cache import cache

from web.utils.response_code import RETCODE
from web.utils.Image import image_code
from celery_tasks.sms.tasks import send_sms
# from celery_tasks.image_code.tasks import check_code
from io import BytesIO
import random


class Send_SMS_view(View):
    def get(self, request, mobile):
        # 放到钩子函数里面校验一下是否有误
        # is_mobile = account.SendSMSModel(data=request.GET)
        # if is_mobile.is_valid():
        #     return http.JsonResponse({"code": RETCODE.MOBILEERR, "errmsg": "手机号不能为空"})
        # 连接数据库
        try:
            conn_redis = get_redis_connection("ver_code")
        except Exception:
            return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "数据库连接异常"})
        # 判断是否重复发送验证码

        if conn_redis.get("send_code_%s" % mobile):
            return http.JsonResponse({"code": RETCODE.THROTTLINGERR, "verify_sms_error_msg": "已经发送过验证码了"})

        if conn_redis.get("send_code_%s" % mobile):
            return http.JsonResponse({"coed": RETCODE.NODATAERR, "err_msg": "发送验证码过于频繁"})
        # 把验证码存到redis中
        code = random.randint(100000, 999999)
        # 创建redis管道
        pi = conn_redis.pipeline()
        pi.setex("code_%s" % mobile, 60 * 3, code)
        pi.setex("send_code_%s" % mobile, 60, 1)
        # 执行
        pi.execute()

        # 发送短信验证码
        send_sms.delay(mobile, code)

        print(code)
        # 返回结果
        return http.JsonResponse({"code": "0", "errmsg": "发送短信验证码成功"})


class ImageCodeView(View):
    def get(self, request, uuid):
        # 连接到redis
        conn = get_redis_connection("ver_code")
        # 查询用户是否已经生成过图形验证码
        if conn.get("code_%s" % uuid):  # 如果存在 就删除用户之前已经生成的验证码
            cache.delete("code_%s" % uuid)
        # 使用celery 异步生成图形验证码提升效率
        img, code = image_code.check_code()
        # 保存到redis当中
        conn.setex("code_%s" % uuid, 60 * 3, code)

        stream = BytesIO()
        img.save(stream, 'png')

        # 保存到session 当中
        # request.session["image_code"] = code
        # request.session.set_expiry(60 * 3)
        # 直接返回一个图片
        return http.HttpResponse(stream.getvalue(), content_type="image/png")
